<?php
class _index
{
	public function initc(){}
    
    public function index()
    {
        View::display('index');
    }

    public function dbHostsName()
    {
        DBConfig::init();
        Response::success(DBConfig::getAllHostsName());
    }

    public function dbDatabase()
    {
        $host = Request::Post('host_name');
        $db = new DB();
        $dbList = $db->getDatabaseList($host);

        Response::success($dbList);
    }

    public function dbTables()
    {
        $host = Request::Post('host_name');
        $dbname = Request::Post('db_name');
        $db = new DB();
        $dbList = $db->getTableList($host, $dbname);
        sort($dbList);

        Response::success($dbList);
    }

    public function dbFields(){
        $host = Request::Post('host_name');
        $dbname = Request::Post('db_name');
        $table = Request::Post('table_name');

        $db = new DB();
        $fieldList = $db->getFieldList($host, $dbname, $table);
        Fun::sort2DArray($fieldList, 'COLUMN_NAME');

        Response::success($fieldList);
    }
    
    /**
     * @throws Exception
     */
    public function sql()
	{
//        Test::link('user')
//            ->fields('uid, username')
//            ->whereOp('uid', '>', 0)
//            ->whereOp('uid', '<=', '11')
//            ->select(FALSE);
//        echo '<pre>';var_dump(Test::$sql);exit;
        
//        Test::link('user')
//            ->fields('uid, username')
//            ->whereGT('uid', 0)
//            ->select()
//            ->data() //php 5.6 +
//            ->group('uid')
//            ->pre();
//        exit;
        
            
//        $sql = 'select * from user';
//        $rs = Test::link('user')
//            ->query($sql)
//            ->data()
//            ->array_column('uid', 'username')
//            ->array_sum()
//            ->data;
//        echo '<pre>';print_r($rs); exit();
        
        
//        $sql = 'select * from user where uid > 1';
//
//        $rs = Test::link('user')
//            ->query($sql)
//            ->getValues('username', 'uid');
//        echo '<pre>';print_r($rs); exit();
        
//        $rs = Test::link('article')
//            ->joinFields('article', 'id, cat_id, title')
//            ->joinFields('article_cats', 'title as cat_title')
//            ->joinTable('article', 'cat_id', 'article_cats', 'id')
//            ->whereGT('article.id', 0)
//            ->limit('5')
//            ->order('article_cats.id asc')
//            ->join()
//            ->getAll();
//        echo '<pre>';
//        print_r($rs);
//        print_r(Test::$sql);
//        exit;
        
//	    $affectRows = Test::link('user')
//            ->where(['uid' => 1])
//            ->updateVal(['age' => 21])
//            ->updateOp('age', 'age', '+', 2)
//            ->addUpdate('age = age + 3')
//            ->update(FALSE)
//            ->affectRows;
//	    //UPDATE test.user set age = 21,age = age + age WHERE (uid = 1)
//	    echo '<pre>';var_dump($affectRows, Test::$sql); exit();
	    
	    //修改
//        $rs = Test::link('user')
//            ->where(['uid' => 2])
//            ->updateVal(['username' => '张三'])
//            ->updateVal(['mobile' => '13100000000']) //此时mobile在最终的SQL中'会'加上引号
//            ->updateVal(['status' => 1]) //此时statys在最终的SQL中'不会'加上引号
//            ->update()
//            ->affectRows;
//        //UPDATE test.user set username = '张三',mobile = '13100000000',status = 1 WHERE (uid = 2)
//        echo '<pre>';var_dump($rs, Test::$sql); exit();
            
	    //插入并返回id
//	    $insertId = Test::link('user')
//        ->insert(['username' => '王五', 'age' => 18])
//        ->insertId;
//        //INSERT INTO test.user (username,age) VALUES ('王五',18)
//        echo '<pre>';var_dump($insertId, Test::$sql); exit();

//	    //一次插入多条记录
//        $insertId = Test::link('user')
//            ->insertm('username, age', array(array('李四','19'), array('赵六', '16')))
//            ->insertId;
//        //INSERT INTO test.user (username, age) VALUES ('李四','19'),('赵六','16')
//        //此时 insertId是'李四'的自增id
//        echo '<pre>';var_dump($insertId, Test::$sql); exit();

//	    //replace into
//        $insertId = Test::link('user')
//            ->replace(['uid' => 5, 'username' => 'world'])
//            ->affectRows;
//        //REPLACE INTO test.user (uid,username) VALUES (5,'hello')
//        //之前存在uid = 5的纪录, 此时insertId = 0; 因为插入的数据没有age, 因此sql执行后age变为0
//        echo '<pre>';var_dump($insertId, Test::$sql); exit();

//	    //删除
//        $affectRows = Test::link('user')
//            ->where(array('uid' => 5))
//            ->delete()
//            ->affectRows;
//        //DELETE FROM test.user WHERE (uid = 5)
//        echo '<pre>';var_dump($affectRows, Test::$sql); exit();
//
//        //获取一条记录
//        // >=, order by
//		$rs = Test::link('user')
//			->whereGE('uid', 1)
//			->order('uid desc')
//            ->limit(1)
//            ->select()
//			->getOne();
//		//SELECT * FROM test.user WHERE (uid >= 1)   ORDER BY uid desc LIMIT 1
//        echo '<pre>';var_dump($rs, Test::$sql); exit();

//        //获取一条纪录中的某一个字段的值
//        $rs = Test::link('user')
//            ->whereGE('uid', 1)
//            ->limit(1)
//            ->select()
//            ->getOneValue('username');
//        //SELECT * FROM test.user WHERE (uid >= 1)    LIMIT 1
//        echo '<pre>';var_dump($rs, Test::$sql); exit();
        
        //获取记录数
//        $rs = Test::link('user')
//            ->whereGE('age', 10)
//            ->count();
//        //SELECT COUNT(1) AS N FROM test.user WHERE (age >= 10)
//        echo '<pre>';var_dump($rs, Test::$sql); exit();

//		//获取多条记录
//        // >, limit, order by
//		$rs = Test::link('user')
//            ->fields('age,username')
//			->whereGT('uid', 1)
//            ->order('uid desc')
//			->limit(10)
//			->select()
//			->getAll();
//        //SELECT age,username FROM test.user WHERE (uid > 1)   ORDER BY uid desc LIMIT 10
//        echo '<pre>';var_dump($rs, Test::$sql); exit();

//		//获取多条记录
//        //获取一维数组, 每一项的值是age
//		$rs = Test::link('user')
//            ->fields('age, uid')
//			->whereGE('uid', 1)
//			->limit(10)
//			->select()
//			->getValues('age');
//        //SELECT age, uid FROM test.user WHERE (uid >= 1)    LIMIT 10
//        echo '<pre>';var_dump($rs, Test::$sql); exit();
    
//        //获取多条记录
//        //获取一维数组, 每一项的值是age, 键值是id
//        $rs = Test::link('user')
//            ->fields('age,uid')
//            ->whereGE('uid', 3)
//            ->limit(10)
//            ->select()
//            ->getValues('age', 'uid');
//        //SELECT id,content FROM tiezi WHERE (id >= 1) LIMIT 10
//        echo '<pre>';var_dump($rs, Test::$sql); exit();

//		//获取多条记录
//        // select in
//		$rs = Test::link('user')
//            ->fields('uid,username')
//			->whereIn('uid', [1,2,3,4,5,7,9])
//			->select()//不改写 between and
//			->getAll();
//		//SELECT uid,username FROM test.user WHERE (uid IN ( 1,2,3,4,5,7,9 ))
//        echo '<pre>';var_dump($rs, Test::$sql); exit();

		//获取多条记录
        //改写between and, 1:将数字排序 2:改写成between and 3.用 unin all 联结
//		$rs = Test::link('user')
//            ->fields('uid,username')
//			->whereIn('uid', [1,2,3,4,5,7])
//			->selectIn() //改写select in, 将数字排序并写成between and 最后用 unin all 联结
//			->getAll();
//        //(SELECT uid,username FROM test.user WHERE 1=1 AND (uid BETWEEN 1 AND 5)) UNION ALL (SELECT uid,username FROM test.user WHERE 1=1 AND (uid = 7))
//
//		echo '<pre>';var_dump($rs, Test::$sql, Timer::$list);
        
        //事务
//        $rs = Test::link('article')->getConnect('write')
//            ->beginTransaction(0, 'savepoint')
//            ->where(['id' => 1])->updateVal(['content' => '<p>哈哈哈哈</p>'])->update()
//            ->where(['id' => 2])->updateVal(['content' => '<p>这个论坛可以多级回复, 无极限哟~</p>'])->update()
//            ->commit()
//            ->whereBetween('id', 1, 2)->select()
//            ->getAll();
//        echo '<pre>'; print_r($rs);
    
    
        $rs = Test::link('article')
            ->joinFields('article', 'id, cat_id, title')
            ->joinFields('article_cats', 'title as cat_title')
            
            ->joinAnd('article_cats.id', '>', 10)
            ->joinAnd('article_cats.type', '=', 'abc')
            ->joinTables('article.cat_id', 'article_cats.id', 'inner') //该句执行后会清空joinAnd
            
            ->joinAnd('article.addtime', 'between', '1111111 and 222222')
            ->joinAnd('article.id', 'in', "('123', '234')")
            ->joinTables('article.cat_id', 'article_cats.id', 'inner') //该句执行后会清空joinAnd
            
            ->whereGT('article.id', 0)
            ->limit('5')
            ->order('article_cats.id asc')
            ->join(FALSE);
        echo '<pre>';
        //print_r($rs);
        print_r(Test::$sql);
        exit;
        /**
        SELECT article.id,article.cat_id,article.title, article_cats.title AS cat_title
        FROM test.article
        INNER JOIN article_cats ON article.cat_id = article_cats.id AND article_cats.id > 10 AND article_cats.type = 'abc'
        INNER JOIN article_cats ON article.cat_id = article_cats.id AND (article.addtime BETWEEN 1111111 AND 222222) AND article.id IN ('123', '234')
        WHERE (article.id > 0)
        ORDER BY article_cats.id ASC
        LIMIT 5
         */
            

	}

	public function req()
    {
        echo '<pre>';
        var_dump(Request::Get('a'));
        var_dump(Request::Get('b'));
        var_dump(Request::Post('a'));
        var_dump(Request::Cookie('a'));
        var_dump(Request::Route('a'));

        var_dump(Request::pickData(['a' => 0, 'b' => '', 'c' => '0'], 'get'));
    }

    public function route()
    {
        echo '<pre>';
        var_dump(Request::Route('page'));
    }

	public function response()
	{
		$a = ['list' => [1,2,3,4]];

		Response::notify('页面找不到啦~'); //页面找不到啦~
        Response::redirect('充值成功, 页面即将跳转', 'http://meiju.hearu.top', 3);
        Response::jump('http://meiju.hearu.top'); //直接跳转
        
        //输出固定格式的json数据
        Response::json(10000, '用户列表', $a); //{"code":10000,"msg":"\u7528\u6237\u5217\u8868","data":{"list":[1,2,3,4]}}
        
        //Response::json()的简写, 结构是一样的
        Response::success($a);
        Response::success($a, '用户列表');
        Response::success($a, '用户列表', 20000);
        
        //Response::json()的简写, 结构是一样的
		Response::error('参数错误'); //{"code":"-1","msg":"\u53c2\u6570\u9519\u8bef","data":[]]}
		Response::error('参数错误', $a); //{"code":"-1","msg":"\u53c2\u6570\u9519\u8bef","data":{"list":[1,2,3,4]},"url":""}
		Response::error('参数错误', $a, 20001); //{"code":2001,"msg":"\u53c2\u6570\u9519\u8bef","data":{"list":[1,2,3,4]}}
  
		//返回任意结构的json数据
        Response::jsonReturn($a); //{"list":[1,2,3,4]}
    }

    public function icurl()
    {
        echo '<pre>';

        echo ICurl::ini('http://www.zhangzhibin.com/index/index/ss')
            ->setPort('80')
            ->setExecTimeOut(4)
            ->getRetry('^', 5, 100); //返回结果中不包含"^"字符就重试
        var_dump(ICurl::$reTryCounter);

        echo ICurl::ini('http://www.zhangzhibin.com/index/index/ss')
            ->setPostData(['aaa' => 124, 'bbb' => 456])
            ->postRetry(':', 5, 100);
        var_dump(ICurl::$reTryCounter);

        echo ICurl::ini('http://www.zhangzhibin.com/index/index/ss')
            ->setReferer('http://www.test.com')
            ->setArrayCookie(['a=123', 'b=456'])
            ->setPostData(['aaa' => 124, 'bbb' => 456])
            ->postRetry(':', 5, 100);
        var_dump(ICurl::$reTryCounter);

        echo ICurl::ini('https://www.baidu.com/')
            ->setUserAgent('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36')
            ->ignoreSSL()
            ->setMaxRedirect(3)
            ->setFollowAction(false)
            ->setReferer('http://www.zhangzhibin.com')
            ->get();
        var_dump(ICurl::$error); //array 所有错误
        var_dump(ICurl::getLastError()); // string 最后一个错误
    }

    public function flog()
    {
        FileLog::info('哈哈哈哈');
        FileLog::error(['aaaa'], '这里是日志前缀');

    }

    public function dirlist()
	{
		$rs = Dir::ini(ROOT)->rmPrefix('E:\code\SummerPHP\\');
		echo '<pre>'; print_r($rs);
		$rs = Dir::ini(ROOT)->getList();
		echo '<pre>'; print_r($rs);
	}
	
	public function redis()
    {
        IRedis::getInstance('dev');
        IRedis::getInstance('pro');
        
        echo '<pre>';var_dump(IRedis::$instance);
    }
    
    public function randCode()
    {
        echo Fun::randCode();
        echo Fun::randCode();
    }

    public function verify($value='')
    {
        Request::Get('aa');
        Request::Get('bb');
        Request::Get('cc');
        Request::Get('dd');
        echo '<pre>';var_dump(666);
    }
    
    public function rel()
    {
        $master = [
            ['a' => 1, 'b' => 11],
            ['a' => 2, 'b' => 22],
            ['a' => 3, 'b' => 33],
        ];
        
        $branch1 = [
            ['c' => 11, 'd' => 111],
            ['c' => 22, 'd' => 222],
        ];
        
        $branch2 = ['c'=> 33, 'd' => 333, 'e' => 3333];
        
        //Fun::linkData($master, $branch1, 'b', 'c', 'x');
        Fun::linkData($master, $branch2, 'b', 'c', 'x');
        
        echo '<pre>';print_r($master); exit();
    }
    
    public function xs()
    {
        $query = Request::Post('name', '');
        
        Html::ini();
        $url = Fun::buildUrl('index', 'index', 'xs');
        $form = form::ini()
            ->setAction($url)
            ->setMethod('post');
        
        $input = input::ini()
            ->setName('name')
            ->setType('text')
            ->setValue($query);
    
        $form->append($input);
        $html = $form->out();
        echo $html;
        
        
        if (!empty($query)) {
            require('/usr/local/web/xunsearch/sdk/php/lib/XS.php');
            $xs = new XS('zhongyao');
            $search = $xs->search;
    
            //$query = '黄芪';
            $docs = $search->setQuery($query)
                ->addWeight('name', $query)
                ->setLimit(5)
                ->search();
    
            $list = array();
    
            foreach ($docs as $doc)
            {
                $list[] = array(
                    'id' => $doc->f('id'),
                    'cate' => $doc->f('cate'),
                    'name' => $doc->f('name'),
                    'gongxiao' => $doc->f('gongxiao'),
                    'bingzheng' => $doc->f('bingzheng'),
                );
            }
    
            echo '<pre>';
            print_r($list);
        }
        
        /*
        [0] => XSDocument Object
        (
            [_data:XSDocument:private] => Array
                (
                    [id] => 304
                    [cate] => 45
                    [name] => 黄芪
                    [gongxiao] => 补气健脾，升阳举陷，益气固表，利水消肿，托毒生肌
                    [bingzheng] => 1. 肺脾气虚证。2. 肺气虚证。3. 气虚自汗。4. 气血亏虚，疮疡难溃难腐，或久溃难敛。
                    [miaoshu] => 补气药，具有补气的功效，能补益脏气以纠正人体脏气虚衰的病理倾向。补气人参太子参，黄芪白术与党参，甘草扁豆淮山药，饴糖大枣西洋参。
                )

            [_terms:XSDocument:private] =>
            [_texts:XSDocument:private] =>
            [_charset:XSDocument:private] => UTF-8
            [_meta:XSDocument:private] => Array
                (
                    [docid] => 304
                    [rank] => 1
                    [ccount] => 0
                    [percent] => 100
                    [weight] => 9.8954057693481
                )

        )
         * */
    }

    public function uuCode()
    {
        echo UniqueCode::getUserCode();
        echo '<br>';
        echo UniqueCode::$id;
        echo '<br>';
        echo Model::$currentSql;
    }
}